package com.guigu.community.controller;

import com.github.pagehelper.PageInfo;
import com.guigu.community.Dto.OrderDto;
import com.guigu.community.controller.util.NumberUtils;
import com.guigu.community.pojo.OrderItems;
import com.guigu.community.pojo.Orders;
import com.guigu.community.service.CartsService;
import com.guigu.community.service.OrderItemsService;
import com.guigu.community.service.OrderService;
import com.guigu.community.vo.OrderVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

@RestController
@CrossOrigin
@RequestMapping("/order")
public class OrderController{
    @Autowired
    private OrderService orderService;
    @Autowired
    private OrderItemsService orderItemsService;
    @Autowired
    private CartsService cartsService;
    @Autowired
    private NumberUtils numberUtils;

    @PostMapping("/addOrder")
    public Integer addOrder(@RequestBody OrderDto orderDto){
        String id = numberUtils.generateDocumentId("211");
        orderDto.setOrderId(id);
        orderDto.setOrderTime(new Date());
        orderDto.setStatus(0);//订单状态在点击添加时默认为0：待发货

        List<OrderItems> items = orderDto.getItems();
        BigDecimal totalAmount = new BigDecimal(0);//商品总金额
        Integer totalNumber = 0;//商品总数量

        for (int i = 0; i < items.size(); i++) {
            OrderItems orderItems = items.get(i);
            totalAmount = totalAmount.add(orderItems.getSubtotal());
            totalNumber += orderItems.getSum();
        }
        orderDto.setTotalAmount(totalAmount); // 主表记录总金额
        orderDto.setTotalNumber(totalNumber); // 主表记录总数量
        boolean save = orderService.save(orderDto);

        //向订单详情表插入
        Integer id1 = orderDto.getId();//获取订单表的id
        for (int i = 0; i < items.size(); i++) {
            OrderItems orderItems = items.get(i);
            //清空ID
            orderItems.setOrderItemId(null);
            //设置父级编号
            orderItems.setParentId(id1);
            orderItemsService.save(orderItems);

            //在添加完订单表和订单详细表之后把购物车的数据删除
            cartsService.removeById(orderItems.getCartId());
        }

        if (save)
            return orderDto.getId();
        return null;
    }


    //根据id查询订单表
    @PostMapping("selectOrderId/{oid}")
    public Orders selectOrderId(@PathVariable Integer oid){
        return orderService.getById(oid);
    }

    //根据UserId查询订单
    @PostMapping("selectOrderItems/{current}/{pageSize}")
    public PageInfo selectOrderItems(@PathVariable Integer current,
                                     @PathVariable Integer pageSize,
                                     @RequestBody OrderVo orderVo){
        return orderService.queryOrderItems(current, pageSize, orderVo);
    }
}
